import requests
import os

def upload_and_analyze(file_path):
    # 1. 上传文件
    upload_url = "https://open.bigmodel.cn/api/paas/v4/files"
    with open(file_path, "rb") as f:
        files = {"file": (os.path.basename(file_path), f, "application/pdf")}
        headers = {"Authorization": "Bearer 08d5ef7e0b1d4d4c876ba4161ba8e706.jD7GaF7DCeQ5esXz"}
        upload_response = requests.post(upload_url, files=files, headers=headers)
        
        # 添加错误处理
        response_data = upload_response.json()
        print("API响应:", response_data)  # 打印实际响应内容
        
        if "id" not in response_data:
            raise Exception(f"文件上传失败: {response_data}")
            
        file_id = response_data["id"]

    # 2. 分析文件
    chat_url = "https://open.bigmodel.cn/api/paas/v4/chat/completions"
    payload = {
        "model": "glm-4.5v",
        "messages": [
            {
                "role": "user",
                "content": [
                    {
                        "type": "file_url",
                        "file_url": {"url": f"file://{file_id}"}
                    },
                    {
                        "type": "text",
                        "text": "请分析这个数据手册的内容"
                    }
                ]
            }
        ]
    }
    response = requests.post(chat_url, json=payload, headers=headers)
    return response.json()

def main():
    result = upload_and_analyze("datasheet/Ams-Osram-AS5600L-DS000545_EN.pdf")  # 替换为实际文件路径
    print(result)

if __name__ == "__main__":
    main()
